import cv2
import numpy as np

path = '../../../../large_data/video/lane/lane.avi'
red = cv2.VideoCapture(path)

while (1):
    ret,image = red.read()

    if image is None:
        break
    #cv2.imshow('image',image)

    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    #cv2.imshow('gray', gray)

    # 模糊图片和消除噪声
    blur = cv2.GaussianBlur(gray, (5, 5), 0)
    dil= cv2.dilate(blur, (3, 3), iterations=5)

    # 边缘检测
    canny_img = cv2.Canny(dil, 50, 150)
    #cv2.imshow('canny_img', canny_img)

    # 过滤出roi以外图
    mask = np.zeros_like(canny_img)
    # cv2.imshow('mask',mask)

    h = image.shape[0]
    w = image.shape[1]

    poly = np.array([[0, 450], [350, 300], [550, 300], [856, 450]])
    cv2.fillPoly(mask, [poly], 255)
    # cv2.imshow('mask2',mask)

    dst = cv2.bitwise_and(canny_img, mask)
    cv2.imshow('dst',dst)

    #获取车道线找到图中的2条线
    rho = 2
    theta = np.pi / 180
    threshold = 20
    min_line_length = 0

    max_line_gap = 300
    lines = cv2.HoughLinesP(dst, rho, theta, threshold, np.array([]),minLineLength=min_line_length, maxLineGap=max_line_gap)

    dst1 = np.zeros((h, w, 3), dtype=np.uint8)

    filtered_lines = []

    if lines is None:
        break

    for line in lines:
        for x1, y1, x2, y2 in line:
            filtered_lines.append([[x1, y1, x2, y2]])
            cv2.line(dst1, (x1, y1), (x2, y2), (0, 0, 255), 2)

    #少一个步骤
    #现在图中不仅有多条线,所以思路是划分左右车道,对左右车道的两条线进行填充

    #cv2.imshow('dst1',dst1)

    #车道线与原图叠加
    dst2 = cv2.addWeighted(image, 0.8, dst1, 1, 0)
    cv2.imshow('result', dst2)

    if cv2.waitKey(5) & 0xff == 27:
        break

red.release()
cv2.destroyAllWindows()
